//
//  NetworkingBaseInterceptor.m
//  YiJuZhangShou
//
//  Created by 冷悦 on 16/3/6.
//  Copyright © 2016年 Uranus. All rights reserved.
//

#import "NetworkingBaseInterceptor.h"
#import "RequestGenerator.h"
#import "SyncTimer.h"
#import "LogDataObject.h"
#import "AppContext.h"
#import "CoreDataUtil.h"
#import "YiJuApiMapping.h"

@implementation NetworkingBaseInterceptor

#pragma mark - Private
- (NSString *)generateRequestId:(NetworkingBaseManager *)manager{
    NSDictionary *params = manager.params;
    RequestType requestType = manager.requestType;
    NSString *apiName = manager.apiName;
    NSString *requestId = [[RequestGenerator sharedInstance]generateRequestId:params
                                                                  requestType:requestType
                                                                   andAPIName:apiName];
    
    return requestId;
}

- (void)manager:(NetworkingBaseManager *)manager afterPerformSuccessWithResponse:(NSDictionary *)responseParams{
    NSString *requestId = [self generateRequestId:manager];
    DDLogInfo(@"请求id:%@",requestId);
    [[RequestGenerator sharedInstance] deleteProcessingRequest:requestId];
}

- (void)manager:(NetworkingBaseManager *)manager beforePerformFailWithResponse:(NSError *)error{
    NSString *requestId = [self generateRequestId:manager];
    [[RequestGenerator sharedInstance] deleteProcessingRequest:requestId];
}

- (void)afterCallingAPIWithManager:(NetworkingBaseManager *)manager{
    long long timestamp = [SyncTimer sharedInstance].systemTimeMillis;
    NSInteger userId = [AppContext sharedInstance].userId;
    NSString *apiName = manager.apiName;
    
    YiJuApiMapping *yiJuApiMapping = [[YiJuApiMapping alloc] initWithUrlStr:apiName];
    NSString *mappingApi = [yiJuApiMapping doMapping];
    //数据返回成功，保存本次行为记录
    NSString *api = [NSString stringWithFormat:@"%@ %@",mappingApi,[self getRequestStringWithRequestType:manager.requestType]];
    LogDataObject *logDataObject = [[LogDataObject alloc] initWithUserId:userId api:api andTimstamp:timestamp];
    CoreDataUtil *coreDataUtil = [CoreDataUtil sharedInstance];
    [coreDataUtil.logs addObject:logDataObject];

}

- (NSString *)getRequestStringWithRequestType:(RequestType)requestType{
    NSString *requestString = nil;
    switch (requestType) {
        case HTTP_PUT:
            requestString = @"PUT";
            break;
        case HTTP_GET:
            requestString = @"GET";
            break;
        case HTTP_DELETE:
            requestString = @"DELETE";
            break;
        case HTTP_POST:
            requestString = @"POST";
            break;
        case HTTP_UPLOAD:
            requestString = @"POST";
            break;
        default:
            NSAssert(NO, @"未设置Http请求类型（GET,POST,PUT,DELETE）");
            break;
    }
    return requestString;
}


@end
